package q_152_max_product_subarray;

import org.junit.Assert;
import org.junit.Test;

/**
 * @author : dormi330
 * @since : 21/12/06
 */
public class Main {

    @Test
    public void test1() {
        Assert.assertEquals(6, new Solution().maxProduct(new int[]{2, 3, -2, 4}));
    }

    @Test
    public void test2() {
        Assert.assertEquals(16, new Solution().maxProduct(new int[]{3, 3, -1, 4, 4}));
    }

    @Test
    public void test3() {
        Assert.assertEquals(0, new Solution().maxProduct(new int[]{-1, 0}));
    }

    @Test
    public void test4() {
        Assert.assertEquals(25, new Solution().maxProduct(new int[]{3, 3, -1, 4, 4, 0, 5, 5}));
    }

    @Test
    public void test5() {
        Assert.assertEquals(50, new Solution().maxProduct(new int[]{3, 3, -1, 4, 4, 0, 5, 5, -1, 2, -1}));
    }

    @Test
    public void test6() {
        Assert.assertEquals(2, new Solution().maxProduct(new int[]{0, 2}));
    }

    @Test
    public void test7() {
        Assert.assertEquals(2, new Solution().maxProduct(new int[]{0, 0, 2}));
    }

    @Test
    public void test8() {
        Assert.assertEquals(24, new Solution().maxProduct(new int[]{2, -5, -2, -4, 3}));
    }

    @Test
    public void test9() {
        Assert.assertEquals(-1, new Solution().maxProduct(new int[]{-1}));
    }

    class Solution {

        public int maxProduct(int[] nums) {
            if (nums.length == 0) {
                return 0;
            }

            int max = 1;
            int res = nums[0];
            for (int i = 0; i < nums.length; i++) {
                max *= nums[i];
                res = Math.max(res, max);
                if (max == 0) {
                    max = 1;
                }
            }

            max = 1;
            for (int i = nums.length - 1; i >= 0; i--) {
                max *= nums[i];
                res = Math.max(res, max);
                if (max == 0) {
                    max = 1;
                }
            }

            return res;
        }
    }
}


